from flask import blueprints, render_template, request, jsonify, session, redirect, url_for
from exts import mail, db
from flask_mail import Message
import random
from models import UserModel
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_user, login_required, logout_user

bp = blueprints.Blueprint('auth', __name__, url_prefix='/auth')


@bp.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        data = request.get_json()
        email = data.get('email')
        password = data.get('password')
        user = UserModel.query.filter_by(email=email).first()
        if not user:
            return jsonify({'code': 400, 'data': None, 'message': '用户不存在'})
        if check_password_hash(user.password, password):
            login_user(user)
            return jsonify({'code': 200, 'data': None, 'message': '登录成功'})
        else:
            return jsonify({'code': 400, 'data': None, 'message': '用户名或密码错误'})

    if request.method == 'GET':
        return render_template('login.html')


@bp.route('/logout', methods=['GET'])
@login_required
def logout():
    logout_user()
    return render_template('login.html')


@bp.route('/register', methods=['POST', 'GET'])
def register():
    if request.method == 'POST':
        data = request.get_json()
        user_captcha = data.get('captcha')  # 用户输入的验证码
        try:
            email = session.get('email')
        except AttributeError as e:
            return jsonify({'code': 400, 'data': None, 'message': '验证码已失效，请重新发送验证码'})
        password = data.get('password')

        # 从 session 获取之前生成的验证码
        correct_captcha = session.get('captcha')

        if not correct_captcha:
            return jsonify({'code': 400, 'data': None, 'message': '验证码已失效，请重新发送验证码'})

        if str(user_captcha) == str(correct_captcha):
            try:
                # 验证码正确，继续处理注册逻辑， md5加密
                user = UserModel()
                user = UserModel(email=email, password=generate_password_hash(password))
                db.session.add(user)
                db.session.commit()
                return jsonify({'code': 200, 'data': None, 'message': '注册成功！'})
            except Exception as e:
                return jsonify({'code': 500, 'data': None, 'message': f'注册失败，请重试{str(e)}'})
        else:
            # 验证码错误
            return jsonify({'code': 400, 'data': None, 'message': '验证码错误，请重新输入'})
    return render_template('register.html')


@bp.route('/send-captcha', methods=['POST'])
def mail_test():
    data = request.get_json()  # 获取前端传递的数据
    email = data.get('email')

    if not email:
        return jsonify({'code': 400, 'message': '邮箱地址不能为空'})

    try:
        # 调用发送验证码函数
        captcha = random.randint(100000, 999999)
        # 保存验证码到 session
        session['captcha'] = captcha
        session['email'] = email

        # 创建邮件对象并发送
        msg = Message(subject='小橙刷考', recipients=[email],
                      body=f"你的验证码是： {captcha}，1分钟内有效，不要给别人看哦。")

        mail.send(msg)  # 发送邮件

        # 假设验证码发送成功，返回成功消息
        return jsonify({'code': 200, 'message': '验证码已发送'})
    except Exception as e:
        # 处理发送失败的情况，并确保只返回字符串形式的错误消息
        return jsonify({'code': 500, 'message': f'验证码发送失败: {str(e)}'})
